/*
 * @Author: 小花
 * @Date: 2022-04-22 16:49:24
 * @LastEditors: 小花
 * @LastEditTime: 2022-04-23 09:51:35
 * @FilePath: /vue3-teap/src/plugins/xlsx/xlsx.ts
 * @Description:
 */
import { UploadRawFile } from 'element-plus'
import * as XLSX from 'xlsx'

export function replaceTitle (data: any[], target: { [key: string]: any }): any[] {
  data.forEach(item => {
    Object.keys(target).forEach(key => {
      const newkey = target[key]
      if (newkey) {
        item[newkey] = item[key]
        delete item[key]
      }
    })
  })
  return data
}
interface IConfig extends XLSX.JSON2SheetOpts {
  replaceTitle?: object
}
/**
 * @description: 导出EXCEL
 * @param {T} data 数组对象类型 数据
 * @param {*} fileName 文件名
 * @param {object} target 替换标题行 { sourceTitle: 'targetTitle' }
 * @return {*}
 */
export function exportXlsx<T = any> (data: T[], fileName = 'example.xlsx', config: IConfig): Promise<boolean> {
  return new Promise((resolve, reject) => {
    try {
      config.replaceTitle && replaceTitle(data, config.replaceTitle)
      if (!fileName.includes('.xlsx')) fileName = fileName.concat('.xlsx')
      const workSheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(data, config)
      const workBook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workBook, workSheet)
      XLSX.writeFileXLSX(workBook, fileName)
      resolve(true)
    } catch (e) {
      reject(e)
    }
  })
}

export function importExcelFromBuffer<Item = any> (excelRcFileBuffer: ArrayBuffer): Item[] {
  // 读取表格对象
  const workbook = XLSX.read(excelRcFileBuffer, { type: 'buffer' })
  // 找到第一张表
  const sheetNames = workbook.SheetNames
  const sheet1 = workbook.Sheets[sheetNames[0]]
  // 读取内容
  return XLSX.utils.sheet_to_json(sheet1)
}
